package com.leyou.cart.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.cart.entity.MyCollections;
import com.leyou.cart.mapper.CollectionsMapper;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.UserHolder;
import com.leyou.common.exception.LyException;
import com.leyou.common.exception.enums.ExceptionEnum;
import com.leyou.common.pojo.PageResult;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.IdWorker;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.client.ItemClient;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author RudolfHugh
 * @since 2020/5/26 15:46
 */
@Service
public class CollectionsService {

  private CollectionsMapper collectionsMapper;

  private ItemClient itemClient;

  private IdWorker idWorker;

  @Autowired
  public void setIdWorker(IdWorker idWorker) {
    this.idWorker = idWorker;
  }

  @Autowired
  public void setCollectionsMapper(CollectionsMapper collectionsMapper) {
    this.collectionsMapper = collectionsMapper;
  }

  @Autowired
  public void setItemClient(ItemClient itemClient) {
    this.itemClient = itemClient;
  }

  /**
   * 添加收藏
   *
   * @param spuId 商品Id
   */
  public void addCollections(Long spuId) {
    UserInfo user = UserHolder.getUser();
    if (user == null) {
      throw new LyException(ExceptionEnum.UNAUTHORIZED);
    }

    //查询最新sku的信息
    Sku sku = itemClient.findSkuListByIds(Collections.singletonList(spuId)).get(0);
    if (sku == null) {
      throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
    }

    // 查询该用户是否重复收藏
    Example example = new Example(MyCollections.class);
    Example.Criteria criteria = example.createCriteria();
    criteria.andEqualTo("userId", user.getId());
    criteria.andEqualTo("skuId", sku.getId());
    List<MyCollections> myCollectionsList = collectionsMapper.selectByExample(example);
    if (!CollectionUtils.isEmpty(myCollectionsList)) {
      throw new LyException(ExceptionEnum.REPEAT_TO_ADD);
    }

    MyCollections myCollections = BeanHelper.copyProperties(sku, MyCollections.class);

    // 将规则参数Id转为参数名字
    String oldOwnSpec = myCollections.getOwnSpec();
    Map<String, String> map1 = JsonUtils.toMap(oldOwnSpec, String.class, String.class);
    LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
    map1.entrySet()
        .forEach(
            m -> {
              SpecParam specParam = itemClient.findSpecParamById(Long.valueOf(m.getKey()));
              if (specParam == null) {
                throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
              }
              linkedHashMap.put(specParam.getName(), m.getValue());
            });
    String newOwnSpec = JsonUtils.toString(linkedHashMap);

    myCollections.setOwnSpec(newOwnSpec);
    myCollections.setId(idWorker.nextId());
    myCollections.setUserId(user.getId());
    myCollections.setSkuId(sku.getId());

    int count = collectionsMapper.insert(myCollections);
    if (count != 1) {
      throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
    }
  }

  /**
   * 查询用户的收藏
   *
   * @return 收藏对象集合
   */
  public PageResult<MyCollections> queryMyCollections(Integer page, Integer rows) {
    UserInfo user = UserHolder.getUser();
    if (user == null) {
      throw new LyException(ExceptionEnum.UNAUTHORIZED);
    }

    PageHelper.startPage(page, rows);

    // 这里封装一个排序条件,防止limit后的结果出现乱序以及重复的情况
    Example example = new Example(MyCollections.class);
    Example.Criteria criteria = example.createCriteria();
    criteria.andEqualTo("userId", user.getId());
    example.setOrderByClause("id asc");
    List<MyCollections> collectionsList = collectionsMapper.selectByExample(example);

    if (CollectionUtils.isEmpty(collectionsList)) {
      // 用户没有收藏任何商品
      throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
    }

    //判断sku是否下架或者被修改(修改后的sku的id是会变化的)
    collectionsList.forEach(
        myCollections -> {
          Sku newSku = itemClient.findSkuById(myCollections.getSkuId());
          if (newSku != null) {
            myCollections.setNewSku(newSku);
          }
        });

    PageInfo<MyCollections> pageInfo = new PageInfo<>(collectionsList);
    long total = pageInfo.getTotal(); // 总记录数
    int totalPages = pageInfo.getPages(); // 总页数
    List<MyCollections> list = pageInfo.getList(); // 当前页数据
    return new PageResult<MyCollections>(total, totalPages, list);
  }

  /**
   * 取消收藏
   *
   * @param spuId 商品id
   */
  public void deleteCollections(Long spuId) {
    UserInfo user = UserHolder.getUser();
    if (user == null) {
      throw new LyException(ExceptionEnum.UNAUTHORIZED);
    }

    Sku sku = itemClient.findSkuListByIds(Collections.singletonList(spuId)).get(0);
    if (sku == null) {
      throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
    }

    Example example = new Example(MyCollections.class);
    Example.Criteria criteria = example.createCriteria();
    criteria.andEqualTo("userId", user.getId());
    criteria.andEqualTo("skuId", sku.getId());
    int count = collectionsMapper.deleteByExample(example);
    if (count != 1) {
      throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
    }
  }
}
